<template>
    <view>
        <van-sticky>
            <view class="flexs align-center head_box">
                <view class="head_title text-center" @tap="gethead" :data-type="item.type" v-for="(item, index) in headlist" :key="index">
                    <view :class="index1 == item.type ? 'text-lg text-bold' : 'text-df text-darkGrey'">{{ item.name }}</view>

                    <view :class="'line_box radius ' + (index1 == item.type ? 'bg-orange' : '')" style="margin: 6rpx auto 0 auto"></view>
                </view>
            </view>
        </van-sticky>
        <view style="height: 90rpx"></view>
        <view class="pages">
            <van-empty v-if="list.length == 0" description="暂无数据" />
            <view class="listbox" v-for="(items, index) in list" :key="index">
                <view class="listbox1 padding-tb-xs">
                    <view class="centers" @tap.stop.prevent="copywxtap" :data-id="items.orderSn">
                        <view class="text-darkGray text-sm mr-10">订单号：{{ items.orderSn }}</view>
                        <image class="icon-32" mode="scaleToFill" :src="imgUrl + 'copy_order.png'"></image>
                    </view>
                    <view class="text-sm" style="color: #ff1717">
                        {{
                            items.status == 0
                                ? '待付款'
                                : items.status == 1
                                ? '待发货'
                                : items.status == 2 && items.deliveryType == 2
                                ? '待自提'
                                : items.status == 2
                                ? '待收货'
                                : items.status == 3
                                ? '已完成'
                                : items.status == 6
                                ? '已退款'
                                : items.status == 8
                                ? '退款中'
                                : items.status == 9
                                ? '退款失败'
                                : '已关闭'
                        }}
                    </view>
                </view>

                <view
                    :class="'listbox1 ' + (items.mallOrderItemDtos.length > 2 && index == 1 ? '' : 'border_bottom')"
                    v-if="index < 2"
                    @tap="goorderdetailed"
                    :data-item="items"
                    v-for="(inner, index1) in items.mallOrderItemDtos"
                    :key="index1"
                >
                    <image class="listbox2left" :src="inner.productPic"></image>

                    <view class="margin-left-sm" style="width: 490rpx">
                        <view class="text-black text-sm text-tline">{{ inner.productName }}</view>
                        <view class="text-darkGray text-sm flexs justify-between margin-top-xs">
                            <view>{{ inner.spType }}</view>
                            <view>x{{ inner.productQuantity }}</view>
                        </view>
                        <view :class="checkMaker && inner.priceMaker != '0.00' && inner.priceMaker ? 'markerpic' : 'markerpic_no'">
                            <block v-if="checkMaker && inner.priceMaker != '0.00' && inner.priceMaker">
                                <text class="text-orange">创客</text>
                                <text style="color: #ff1717">￥{{ inner.priceMaker }}</text>
                                <text v-if="inner.integration">+</text>
                            </block>
                            <block v-else>
                                <block v-if="inner.productPrice && inner.productPrice > 0">
                                    {{ inner.productPrice }}
                                    <block v-if="inner.integration">+</block>
                                </block>
                            </block>
                            <view v-if="inner.integration">
                                <image src="/static/images/douzi.png" style="width: 20rpx; height: 18rpx; margin: 0 10rpx"></image>
                                <text>{{ inner.integration || '0' }}</text>
                            </view>
                            <view v-else>
                                <block v-if="items.useIntegration && items.useIntegration > 0">
                                    <image src="/static/images/douzi.png" style="width: 20rpx; height: 18rpx; margin: 0 10rpx"></image>
                                    <text>{{ items.useIntegration }}</text>
                                </block>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="text-center text-df border_bottom padding-bottom-sm" @tap="goorderdetailed" :data-item="items" v-if="items.mallOrderItemDtos.length > 2">
                    查看更多
                </view>

                <view class="listbox2">
                    <view class="text-right">
                        <text class="text-black text-df">共{{ items.productNum }}件商品，总价：</text>
                        <text class="text-df" style="color: #ff1717">¥{{ items.totalAmount }}</text>
                    </view>
                    <view class="flexs" style="justify-content: flex-end">
                        <view class="remindbtn2 text-dm" v-if="items.status == 0" :data-status="items.status" data-type="1" :data-item="items" @tap.stop.prevent="czorder">
                            取消订单
                        </view>
                        <view class="remindbtn1 text-dm" v-if="items.status == 0" :data-status="items.status" data-type="2" :data-item="items" @tap="czorder">
                            <!-- data-status="{{items.status}}" data-type="2" data-item="{{items}}" bindtap="czorder" -->
                            去付款
                        </view>
                        <block v-if="items.status == 1">
                            <view class="remindbtn1 text-dm" v-if="items.remindType == 1" :data-status="items.status" data-type="3" :data-item="items" @tap.stop.prevent="czorder">
                                提醒发货
                            </view>
                            <view class="remindbtn2 text-dm" v-if="items.remindType == 2">已提醒平台发货</view>
                        </block>
                        <view
                            class="remindbtn1 text-dm"
                            v-if="items.deliveryType != 2 && items.status == 2"
                            :data-status="items.status"
                            data-type="4"
                            :data-item="items"
                            @tap.stop.prevent="czorder"
                        >
                            确认收货
                        </view>
                        <view
                            class="remindbtn2 text-dm"
                            v-if="items.status == 3 || items.status == 4 || items.status == 6"
                            :data-status="items.status"
                            data-type="5"
                            :data-item="items"
                            @tap.stop.prevent="czorder"
                        >
                            删除订单
                        </view>
                        <view
                            class="remindbtn2 text-dm margin-left-xs"
                            v-if="items.deliveryType == 2 && items.status == 2"
                            :data-orderSn="items.orderSn"
                            :data-storeId="item.storeId"
                            data-type="6"
                            :data-item="items"
                            @tap.stop.prevent="czorder"
                        >
                            提货码
                        </view>
                    </view>
                </view>
            </view>
            <!-- 结束 -->

            <!-- 下面一个订单多个商品,查看更多 -->
            <!-- <view class="listbox">
      <view class="listbox1">
        <view class="text-darkGray text-sm">订单号：9029498485839</view>
        <view class="text-sm" style="color:#FF8722;">待发货</view>
      </view>

      <view class="listbox1 border_bottom" bindtap="goorderdetailed">
        <view>
          <image class="listbox2left" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201201%2F01%2F20120101110848_keuNr.thumb.700_0.jpg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633341106&t=e0fbd77b05f916df75e4be468e170e5d"></image>
        </view>
        <view class="margin-left-sm">
          <view class="text-black text-sm ">海氏海诺*一次性使用医用防护口罩20片装（10片/包*2）</view>
          <view class="text-darkGray text-sm flexs justify-between margin-top-xs"><view>颜色：红色</view><view>x1</view></view>
          <view class="red17 text-df margin-top-xs flexs align-center"> <image src="../../images/douzi.png" class="douzis"></image><view>1000</view></view>
        </view>
      </view>

      <view class="listbox1 border_bottom" bindtap="goorderdetailed">
        <view>
          <image class="listbox2left" src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201201%2F01%2F20120101110848_keuNr.thumb.700_0.jpg&refer=http%3A%2F%2Fcdn.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633341106&t=e0fbd77b05f916df75e4be468e170e5d"></image>
        </view>
        <view class="margin-left-sm">
          <view class="text-black text-sm ">海氏海诺*一次性使用医用防护口罩20片装（10片/包*2）</view>
          <view class="text-darkGray text-sm flexs justify-between margin-top-xs"><view>颜色：红色</view><view>x1</view></view>
          <view class="red17 text-df margin-top-xs flexs align-center"> <image src="../../images/douzi.png" class="douzis"></image><view>1000</view></view>
        </view>
      </view>

      <view class="text-center text-df text-black">查看更多</view>

      <view class="listbox2">
        <view class="text-right">
          <text class="text-black text-df">共1件商品，总价：</text>
          <text class="text-df" style="color:#FF1717;">¥19.00</text>
        </view>
        <view class="flexs" style="justify-content:flex-end;">
          <view class="remindbtn2 text-df ">
              取消订单
          </view>
          <view class="remindbtn1 text-df ">
              提醒发货
          </view>
        </view>
      </view>

    </view> -->
            <!-- 结束 -->
        </view>
        <view style="height: 40rpx"></view>
    </view>
</template>

<script>
const _request = require('../../utils/request.js');

const moment = require('../../utils/moment.min');

const app = getApp();
export default {
    //status订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单; 6已退款  9退款失败，8退款中
    data() {
        return {
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            list: [],

            //订单列表
            headlist: [
                {
                    name: '全部',
                    type: -1
                },
                {
                    name: '待付款',
                    type: 0
                },
                {
                    name: '待发货',
                    type: 1
                },
                {
                    name: '待收货',
                    type: 2
                },
                {
                    name: '退换/售后',
                    type: 3
                }
            ],

            index1: -1,
            pageNo: 0,
            total: 0,
            reload: false,
            isBack: true,
            checkMaker: false,

            //是否是创客用户
            clone_item: null,

            //全局img路径
            imgUrl: app.globalData.imgUrl,

            inner: {
                productPic: '',
                productName: '',
                spType: '',
                productQuantity: '',
                priceMaker: '',
                integration: '',
                productPrice: ''
            }
        };
    },
    onLoad: function (options) {
        if (options.type) {
            this.setData({
                index1: options.type
            });
        }

        if (options._item) {
            // 存在则不返回my/index
            this.setData({
                clone_item: options._item
            });
        }
    },
    onShow: function () {
        this.setData({
            checkMaker: uni.getStorageSync('maker')?.ismaker || false
        });

        if (this.reload) {
            this.setData({
                pageNo: 0,
                list: []
            });
        }

        this.getlist();
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        // 如果是点击错czorder()和支付成功跳转后就不执行
        if (!this._item || this._item == '_item') {
            uni.reLaunch({
                url: '/firstpages/my/index'
            });
        }
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.setData(
            {
                pageNo: 0
            },
            () => {
                // 获取订单列表接口
                this.getlist();
            }
        );
        uni.stopPullDownRefresh(); //停止下拉刷新
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        // if(this.data.list?.length < this.data.total){
        this.setData(
            {
                pageNo: this.pageNo + 1
            },
            () => {
                // 获取订单列表接口
                this.getlist();
            }
        ); // }
    },
    methods: {
        // 复制邀请码
        copywxtap(e) {
            uni.hideToast({});

            let _this = this;

            uni.setClipboardData({
                data: e.currentTarget.dataset.id,
                success: function (res) {
                    uni.showToast({
                        title: '已复制订单号',
                        icon: 'none'
                    });
                    uni.getClipboardData({
                        //这个api是把拿到的数据放到电脑系统中的
                        success: function (res) {}
                    });
                }
            });
        },

        // 获取订单列表接口
        getlist() {
            _request
                .get(
                    '/mall-order/list',
                    {
                        status: this.index1 > -1 ? Number(this.index1) : '',
                        pageSize: 20,
                        offset: this.pageNo,
                        userId: uni.getStorageSync('userid'),
                        type: ''
                    },
                    app.globalData.mallType
                )
                .then((res) => {
                    if (res.data.code === 200) {
                        var _list = res.data.data;

                        _list.map((items) => {
                            // let _num = 0
                            if (items.productAttr != 2) {
                                items.mallOrderItemDtos.forEach((inner) => {
                                    // _num = Number(inner.productQuantity) + _num
                                    // console.log(JSON.parse(inner.specification));
                                    inner.spObj = JSON.parse(inner.specification);
                                    let list = [];
                                    inner.spObj.forEach((item) => {
                                        list.push(item.key + '：' + item.value);
                                    });
                                    inner.spType = list.join(',');
                                });
                            } //   let lastTime = new moment(items.remindTime || '').format('x')
                            //   let time = new moment().format('x')
                            //   // console.log('diff', lastTime, time, (time-lastTime)/3600/1000)
                            //   let overTime = (time-lastTime)/3600/1000 > 24
                            //   items.showRemind = items.remindType == 1 || (items.remindType == 2 && overTime)
                            //   items.total = _num
                        }); //数据去重

                        let mlist = this.pageNo > 0 ? [...this.list, ..._list] : _list;

                        let deWeight = () => {
                            let map = new Map();

                            for (let item of mlist) {
                                map.set(item.id, item);
                            }

                            return [...map.values()];
                        };

                        mlist = deWeight();
                        this.setData({
                            list: mlist,
                            total: res.data.data?.total || 0
                        });
                    } else {
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none'
                        });
                    }
                });
        },

        // 切换头部
        gethead(e) {
            this.setData(
                {
                    pageNo: 0,
                    list: [],
                    index1: e.currentTarget.dataset.type
                },
                () => {
                    this.getlist();
                }
            );
        },

        // 操作
        czorder(e) {
            var _item = e.currentTarget.dataset.item;
            var that = this;
            this.setData({
                clone_item: _item
            });

            if (e.currentTarget.dataset.type == 1) {
                //点击取消订单
                uni.showModal({
                    title: '温馨提示',
                    content: '确认取消订单?',
                    cancelText: '取消',
                    confirmText: '确认',

                    success(res) {
                        if (res.confirm) {
                            _request
                                .postObj(
                                    '/mall-order/cancelOrder',
                                    {
                                        orderSn: _item.orderSn // userId: wx.getStorageSync('userid')
                                    },
                                    app.globalData.mallType
                                )
                                .then((res) => {
                                    console.log(res);

                                    if (res.data.code === 200) {
                                        that.getlist();
                                    } else {
                                        uni.showToast({
                                            title: res.data.message,
                                            icon: 'none'
                                        });
                                    }
                                });
                        }
                    }
                });
            } else if (e.currentTarget.dataset.type == 2) {
                //去付款
                uni.navigateTo({
                    url:
                        '/shopingmall/payment/payment?orderId=' +
                        _item.id +
                        '&orderSn=' +
                        _item.orderSn +
                        '&realityPayPrice=' +
                        _item.payAmount +
                        '&createordertime=' +
                        _item.createTime +
                        '&type=' +
                        _item.type +
                        '&isLarge=false'
                });
            } else if (e.currentTarget.dataset.type == 3) {
                //提醒发货
                _request
                    .postObj(
                        '/mall-order/remindDelivery',
                        {
                            orderSn: _item.orderSn // userid: wx.getStorageSync('userid'),
                        },
                        app.globalData.mallType
                    )
                    .then((res) => {
                        console.log(res);

                        if (res.data.code === 200) {
                            uni.showToast({
                                title: '已提醒商家发货~',
                                icon: 'none',
                                duration: 2000
                            });
                            setTimeout(() => {
                                that.getlist();
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    });
            } else if (e.currentTarget.dataset.type == 4) {
                //确认收货
                uni.showModal({
                    title: '温馨提示',
                    content: '您确认收到了吗?',
                    cancelText: '取消',
                    confirmText: '确认',

                    success(res) {
                        if (res.confirm) {
                            _request
                                .postObj(
                                    '/mall-order/confirmReceipt',
                                    {
                                        orderSn: _item.orderSn // userId: wx.getStorageSync('userid')
                                    },
                                    app.globalData.mallType
                                )
                                .then((res) => {
                                    if (res.data.code === 200) {
                                        that.getlist();
                                    } else {
                                        uni.showToast({
                                            title: res.data.message,
                                            icon: 'none'
                                        });
                                    }
                                });
                        }
                    }
                });
            } else if (e.currentTarget.dataset.type == 5) {
                //删除订单
                uni.showModal({
                    title: '温馨提示',
                    content: '请确认是否删除订单?',
                    cancelText: '取消',
                    confirmText: '确认',

                    success(res) {
                        if (res.confirm) {
                            _request
                                .postObj(
                                    '/mall-order/deleteOrder',
                                    {
                                        orderSn: _item.orderSn // userId: wx.getStorageSync('userid')
                                    },
                                    app.globalData.mallType
                                )
                                .then((res) => {
                                    if (res.data.code === 200) {
                                        that.getlist();
                                    } else {
                                        uni.showToast({
                                            title: res.data.message,
                                            icon: 'none'
                                        });
                                    }
                                });
                        }
                    }
                });
            } else if (e.currentTarget.dataset.type == 6) {
                //核销订单
                const { item } = e.currentTarget.dataset;
                uni.navigateTo({
                    url: './cancel/cancel?orderSn=' + item.orderSn + '&storeId=' + item.storeId
                });
            }
        },

        goorderdetailed(e) {
            this.setData({
                clone_item: null
            });
            uni.navigateTo({
                url: '/pages/mallorder/orderinfo?orderid=' + e.currentTarget.dataset?.item.id + '&orderSn=' + e.currentTarget.dataset?.item.orderSn
            });
        }
    },
    watch: {
        _item: {
            handler: function (newVal, oldVal) {
                this.clone_item = newVal;
            },

            immediate: true
        }
    }
};
</script>
<style>
.head_box {
    position: fixed;
    left: 0;
    width: 750rpx;
    background-color: #fbfbfb;
    z-index: 99;
    height: 100rpx;
}
.head_title {
    width: 20%;
}
.line_box {
    width: 60rpx;
    height: 8rpx;
}
.pages {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    background-color: #fbfbfb;
}
.listbox {
    padding: 0 20rpx 20rpx 20rpx;
    width: 670rpx;
    background: #fff;
    box-shadow: 2rpx 2rpx 8rpx 0rpx rgba(236, 236, 236, 0.4);
    border-radius: 8rpx;
    justify-content: center;
    margin-top: 20rpx;
}
.listbox1 {
    margin: 20rpx auto 0 auto;
    width: 670rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
}
.border_bottom {
    border-bottom: 1rpx solid #dadada;
}
.listbox2left {
    width: 150rpx;
    height: 150rpx;
}
.red17 {
    color: #ff1717;
}
.douzis {
    width: 24rpx;
    height: 24rpx;
}

.listbox2 {
    width: 670rpx;
    margin-top: 20rpx;
}
.remindbtn1 {
    background: #ff8722;
    color: #fff;
    /* width: 152rpx; */
    height: 52rpx;
    line-height: 52rpx;
    text-align: center;
    margin-top: 10rpx;
    border-radius: 26rpx;
    margin-left: 20rpx;
    padding: 0 24rpx;
}
.remindbtn2 {
    /* width: 152rpx; */
    height: 52rpx;
    line-height: 52rpx;
    text-align: center;
    margin-top: 10rpx;
    border-radius: 26rpx;
    border: 1rpx solid #ff8722;
    color: #ff8722;
    padding: 0 24rpx;
}

.markerpic {
    height: 34rpx;
    background: #fff6ef;
    border: 1rpx solid #ff8722;
    border-radius: 4rpx;
    justify-content: center;
    display: flex;
    align-items: center;
    font-size: 22rpx;
    padding: 0 10rpx;
    width: fit-content;
    margin-top: 20rpx;
}

.markerpic_no {
    font-size: 26rpx;
    color: #ff1717;
    margin-top: 20rpx;
    font-weight: bold;
    display: flex;
}
</style>
